import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_static/shelf_static.dart';
Future<HttpServer> startHttpServer(String filePath) async {
  final file = File(filePath);
  if (!await file.exists()) {
    throw Exception('File does not exist: $filePath');
  }

  final directory = file.parent.path;
  final fileName = file.uri.pathSegments.last;

  final handler = const Pipeline()
      .addMiddleware(logRequests())
      .addHandler((Request request) {
    final uriPath = Uri.decodeComponent(request.url.path);
    if (uriPath == fileName) {
      final staticHandler = createStaticHandler(
        directory,
        serveFilesOutsidePath: true,
        defaultDocument: fileName,
      );
      return staticHandler(request);
    }
    return Response.notFound('File not found');
  });

  final server = await shelf_io.serve(
    handler,
    InternetAddress.anyIPv4,
    8088,
  );

  server!.autoCompress = true;
  print('✅ HTTP server running at http://${server!.address.address}:${server!.port}/$fileName');
  return server!;
}

/// 停止 HTTP 服务器
Future<void> stopHttpServer(HttpServer server) async {
  await server!.close(force: true);
  print('HTTP server has been stopped.');
}

Future<String> getLocalIpAddress() async {
  final interfaces = await NetworkInterface.list(
    type: InternetAddressType.IPv4,
    includeLinkLocal: false,
  );

  for (final interface in interfaces) {
    final name = interface.name.toLowerCase();
    final isWifi = name.contains('wlan') || name.contains('wifi') || name == 'en0';

    if (isWifi) {
      for (final addr in interface.addresses) {
        if (!addr.isLoopback) {
          return addr.address;
        }
      }
    }
  }
  for (final interface in interfaces) {
    for (final addr in interface.addresses) {
      if (!addr.isLoopback) {
        return addr.address;
      }
    }
  }
  return '127.0.0.1';
}


